#include "battlewidget.h"
#include "ui_battlewidget.h"
#include "userwidget.h"
#include <QMessageBox>
#include <QEventLoop>
#include <QJsonDocument>

BattleWidget::BattleWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::BattleWidget),
    m_networkAccessManager(Q_NULLPTR)
{
    ui->setupUi(this);

    connect(this, &BattleWidget::matchSuccess, this, [&]() {qDebug() << 456;});

    m_networkAccessManager = new QNetworkAccessManager();
    QEventLoop eventLoop;
    connect(m_networkAccessManager, &QNetworkAccessManager::finished, this, [&](QNetworkReply *reply) {
        eventLoop.exit();
        m_networkAccessManager->disconnect();
        if (reply->readAll() == QString("true"))
            startMatching();
        else
            QMessageBox::critical(this, u8"匹配失败", u8"更新在线用户表错误，请重试！");
    });
    // 调用接口更新用户匹配状态
    QNetworkRequest request;
    request.setUrl(QUrl(Global::serverIp + QString("/user/change_status?user_id=%1&status=1").arg(Global::userId)));
    m_networkAccessManager->get(request);
    eventLoop.exec();
}

BattleWidget::~BattleWidget()
{
    delete ui;
}

void BattleWidget::closeEvent(QCloseEvent *event)
{
    bool isChangeStatusSuccess = false, isDeleteUserInBattleSuccess = false;
    QEventLoop waitForChangeStatusLoop;
    
    QNetworkAccessManager *nerworkAccessManager1 = new QNetworkAccessManager(this);
    QNetworkAccessManager *nerworkAccessManager2 = new QNetworkAccessManager(this);
    
    connect(nerworkAccessManager1, &QNetworkAccessManager::finished, this, [&]() {
        isChangeStatusSuccess = true;
        if (isChangeStatusSuccess && isDeleteUserInBattleSuccess)
            waitForChangeStatusLoop.exit();
    });
    connect(nerworkAccessManager2, &QNetworkAccessManager::finished, this, [&]() {
        isDeleteUserInBattleSuccess = true;
        if (isChangeStatusSuccess && isDeleteUserInBattleSuccess)
            waitForChangeStatusLoop.exit();
    });
    
    QNetworkRequest request1;
    request1.setUrl(QUrl(Global::serverIp + QString("/user/change_status?user_id=%1&status=0").arg(Global::userId)));
    nerworkAccessManager1->get(request1);
    
    QNetworkRequest request2;
    request2.setUrl(QUrl(Global::serverIp + QString("/user_in_battle/remove_user?user_id=%1").arg(Global::userId)));
    nerworkAccessManager2->get(request2);
    
    waitForChangeStatusLoop.exec();

    Global::userWidget->show();
}

void BattleWidget::startMatching()
{
    bool isMatchSuccess = false;
    while (!isMatchSuccess)
    {

        QEventLoop eventLoop;
        connect(m_networkAccessManager, &QNetworkAccessManager::finished, this, [&](QNetworkReply *reply) {
            m_networkAccessManager->disconnect();
            QByteArray replyArray;
            if (!replyArray.isEmpty())
            {
                m_opponent = QJsonDocument::fromJson(replyArray).object();
                emit matchSuccess();
                isMatchSuccess = true;
            }
            eventLoop.exit();
        });

        // 调用接口获取对手
        QNetworkRequest request1;
        request1.setUrl(QUrl(Global::serverIp + QString("/user/get_user_nearest?user_id=%1").arg(Global::userId)));
        m_networkAccessManager->get(request1);
        QNetworkRequest request2;
        request2.setUrl(QUrl(Global::serverIp + QString("/user/get_user_nearest?user_id=%1").arg(Global::userId)));
        m_networkAccessManager->get(request2);
        eventLoop.exec();
    }
}
